package com.security.oauthfilter;

import com.security.handler.Oauth2ParamsHandler;
import com.security.validator.Oauth2ParamsValidator;
import com.security.vo.OauthBaseVo;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by 陈圣融 on 2017-07-29.
 */

/**
 * /oauth/token参数缺失校验
 */
public class Oauth2ParamsValidateFilter implements Filter {
    private Oauth2ParamsHandler oauth2ParamsHandler = new Oauth2ParamsHandler();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        PathMatcher pathMatcher = new AntPathMatcher();
        if (pathMatcher.match(request.getContextPath() + "/oauth/token", request.getRequestURI())) {
            OauthBaseVo oauthBaseErrorVo = Oauth2ParamsValidator.validate(request.getParameterMap());
            if (oauthBaseErrorVo != null) {

                oauth2ParamsHandler.forwardUnoauth(request, response, oauthBaseErrorVo);
                return;
            }
        };
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }

    public Oauth2ParamsHandler getOauth2ParamsHandler() {
        return oauth2ParamsHandler;
    }

    public void setOauth2ParamsHandler(Oauth2ParamsHandler oauth2ParamsHandler) {
        this.oauth2ParamsHandler = oauth2ParamsHandler;
    }
}
